package me.qiji.uploadify.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 文件上传
 * 
 */
public class UploadifyServlet extends HttpServlet {
	private static final long serialVersionUID = 4387256393682431990L;
	private static final Logger log = LoggerFactory.getLogger(UploadifyServlet.class);
	private static final SimpleDateFormat dateForm = new SimpleDateFormat("yyyy/MM/dd");
	private static final String basedir = "d:/output/hello/";

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8"); // 设置编码
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		testUploadify(request, response);
	}

	/**
	 * @author : liyq_qiji@aliyun.com	奇积奇积变
	 * @time   : 2016年7月14日 下午5:48:19
	 * @param request
	 * @param response
	 */
	public void testUploadify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter pw = response.getWriter();
		JSONObject json = new JSONObject();

		try {
			StringBuffer buffer = new StringBuffer(1024);
			StringBuffer fileUrl = new StringBuffer(1024);
			Date date = new Date();
			buffer.append(basedir).append("/test/").append(dateForm.format(date));
			fileUrl.append("/test/").append(dateForm.format(date));

			File upPath = new File(buffer.toString());
			if (!upPath.exists()) {
				boolean mkdirs = upPath.mkdirs();
				if (!mkdirs) {
					log.info("创建文件夹失败...");
				}
			}

			DiskFileItemFactory fac = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(fac);
			upload.setHeaderEncoding("UTF-8");
			// 获取多个上传文件
			List<?> fileList = upload.parseRequest(request);
			// 遍历上传文件写入磁盘
			Iterator<?> it = fileList.iterator();
			while (it.hasNext()) {
				FileItem fileItem = (FileItem) it.next();
				if (StringUtils.isBlank(fileItem.getName())) {
					continue;
				}
				String oldFileName = fileItem.getName().substring(fileItem.getName().lastIndexOf("\\") + 1);
				int index = oldFileName.lastIndexOf(".");
				String ext = oldFileName.substring(index);

				String fileName = UUID.randomUUID().toString() + ext;
				fileUrl.append("/").append(fileName);
				fileItem.write(new File(buffer.toString(), fileName));

				json.put("result", true);
				json.put("attachment", fileName); // 生成的文件名
				json.put("attachmentPath", fileUrl.toString()); // 
				json.put("attachmentName", oldFileName);// 原文件名
			}

		} catch (Exception e) {
			e.printStackTrace();
			json.put("result", false);
			json.put("error", "上传失败" + e.getMessage());
		}
		pw.print(json.toString());
		pw.flush();
		pw.close();
	}
}
